import { createStore } from 'vuex'
import createPersistedState from 'vuex-persistedstate';
import { registerApi } from '../api/User';

export default createStore({
  state: {
    loggedIn: false, // 默认未登录状态
  },
  mutations: {
    login(state) {
      state.loggedIn = true;
    },
    register(state) {
      state.loggedIn = true;
    },
    logout(state) {
      state.loggedIn = false;
    },
  },
  actions: {

    async register({ commit }, data) {
      try {
        const response = await registerApi(data);
        if (response.code == 200) {
          commit('register');
          // 也可以在这里存储 token 到 localStorage 或 cookie 中
          alert("注册成功");
          const form = {
            hpid: '',
            hpname: '',
            smid: '',
            smname: '',
            price: '',
            orderdate: '',
            telephone: '',
            deadline: '',
            address: '',
            businesshours: ''
          }

          sessionStorage.setItem('userInfo', JSON.stringify(response.data));
          localStorage.setItem('token', response.data.token);
          sessionStorage.setItem('orderdetail', JSON.stringify(form));

        } else {
          console.error('register failed:', response.msg);
        }
      } catch (error) {
        console.error('Error during register:', error);
      }
    },
    async logout({ commit }) {
      sessionStorage.removeItem('userInfo');
      sessionStorage.removeItem('orderdetail');
      sessionStorage.removeItem('reportitem');
      localStorage.removeItem('token');
      commit('logout');
      alert('退出成功');
    },

  },
  getters: {
    isLoggedIn: state => state.loggedIn,
  },
  plugins: [createPersistedState({
    storage: window.localStorage,
  })]
})
